#include "QuFile.h"
#include <QString>
#include <QFile>
#include <QDir>
#include <QDirIterator>

void QuFile::copy(const QString& filePath, const QString& destDir)
{
    QString fileName = QFileInfo(filePath).fileName();
    QString destFilePath = destDir + "/" + fileName;

    // 检测目标文件是否存在，若存在则修改文件名称
    while (QFile::exists(destFilePath)) {
        auto pos = destFilePath.lastIndexOf('.');
        if (pos == -1 || pos < destDir.length())
            pos = destFilePath.length();
        destFilePath.insert(pos, " - 副本");
    }

    QFile::copy(filePath, destFilePath);
}


void QuFile::move(const QString& filePath, const QString& destDir)
{
    copy(filePath, destDir);
    QFile::remove(filePath);
}


std::pair<int, qint64> QuFile::stats(const QString& dir, bool includeSubDirs)
{
    QList<QString> workspace{ dir };
    int files(0);
    qint64 totalSize(0);

    while(!workspace.isEmpty()) {
        QDir d(workspace.front()); workspace.pop_front();

        auto eil = d.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
        foreach(const auto& e, eil) {
            auto path = e.absoluteFilePath();

            if (e.isFile())
                files++, totalSize += e.size();
            else if (e.isDir() && includeSubDirs)
                workspace.push_front(path);
        }
    }

    return { files, totalSize };
}


int QuFile::totalFiles(const QString& dir, bool includeSubDirs)
{
    QDirIterator dirIter(dir, QDir::Files,
                         includeSubDirs ? QDirIterator::Subdirectories : QDirIterator::NoIteratorFlags);

    int res(0);
    while(dirIter.hasNext()) {
        res++;
        dirIter.next();
    }

    return res;
}

#include <QDesktopServices>
#include <QUrl>
void QuFile::shellOpen(const QString& filePath)
{
    // NB: 此处须调用fromLocalFile，而不能直接把filePath传入， 否则当filePath包含空格时，不能执行打开操作
    QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
}
